package com.liubujun.nio;

import org.junit.Test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @Author: liubujun
 * @Date: 2022/2/16 19:57
 */


public class BufferDemo2 {

    @Test
    public void test1(){
        ByteBuffer buffer = ByteBuffer.allocate(10);
        for (int i = 0; i < buffer.capacity(); i++) {
            buffer.put((byte) i);
        }

        //创建子缓冲区
        buffer.position(3);
        buffer.limit(7);
        ByteBuffer slice = buffer.slice();

        //改变子缓冲区内容
        for (int i = 0; i < slice.capacity(); i++) {
            byte b = slice.get(i);
            b *= 10;
            slice.put(i,b);
        }
        buffer.position(0);
        buffer.limit(buffer.capacity());
        while (buffer.remaining() > 0 ) {
            System.out.println(buffer.get());
        }
    }

    @Test
    public void test2(){
        ByteBuffer buffer = ByteBuffer.allocate(10);
        for (int i = 0; i < buffer.capacity(); i++) {
            buffer.put((byte) i);
        }

        ByteBuffer readOnly = buffer.asReadOnlyBuffer();
        for (int i = 0; i < buffer.capacity(); i++) {
            byte b = buffer.get(i);
            b *= 10;
            buffer.put(i,b);
        }

        readOnly.position(0);
        readOnly.limit(buffer.capacity());

        while (readOnly.remaining() > 0 ) {
            System.out.println(readOnly.get());
        }
    }

    @Test
    public void test3() throws Exception {
        String infile = "C:\\Users\\LiuBuJun\\Desktop\\liubujun\\01.txt";
        FileInputStream fin = new FileInputStream(infile);
        FileChannel fileChannel = fin.getChannel();

        String outfile = "C:\\Users\\LiuBuJun\\Desktop\\liubujun\\02.txt";
        FileOutputStream out = new FileOutputStream(outfile);
        FileChannel foutChannel = out.getChannel();

        //创建直接缓冲区
        ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
        while (true) {
            buffer.clear();
            int r = fileChannel.read(buffer);
            if (r == -1 ) {
                break;
            }
            buffer.flip();
            foutChannel.write(buffer);
        }
    }

    static private final int start = 0;
    static private final int size = 1024;



    @Test
    public void test4() throws Exception {
        //创建FileChannel
        RandomAccessFile accessFile = new RandomAccessFile("C:\\Users\\LiuBuJun\\Desktop\\liubujun\\01.txt","rw");
        FileChannel channel = accessFile.getChannel();

        MappedByteBuffer map = channel.map(FileChannel.MapMode.READ_WRITE, start, size);
        map.put(0,(byte) 97);
        map.put(1023,(byte) 122);
        accessFile.close();
    }
}
